/**
 * Copyright 2010 Butin Kirill <kiryaka@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.flexupload.manager
{
	import flash.events.Event;
	import flash.net.FileReference;
	import flash.net.FileReferenceList;
	
	import mx.collections.ArrayCollection;
	
	import org.flexupload.Flexupload;

	public class FileManager
	{
		public static const LOADED_FILES_ARRAY_MAX_LENGTH:int = 2;
		private var fileListst:Array = new Array();
		private var files:ArrayCollection = new ArrayCollection();
		private var loadedFiles:Array = new Array();
		
		public function FileManager(){}
		
		public function addFileList(list:FileReferenceList):void{
			fileListst.push(list);
			for each(var file:FileReference in list.fileList) addFile(file);
		}
		
		
		public function isValid(file:FileReference):Boolean{
			return true;
		}
		
		public function addFile(file:FileReference):void{
			if(!isValid(file))return;
			files.addItem(file);
			Flexupload.getInstance().getUploadStatus().addNewFile(file); // todo refactoring
		}
		
		public function hasFileForUpload():Boolean{
			return loadedFiles.length > 0;
		}	
		
		public function getFileForUpload():FileReference{
			var file:FileReference = loadedFiles.shift();
			loadNewFile();
			return file;
		}
		
		public function start():void{
			loadNewFile();
		}
		private function canWeLoadMoreFiles():Boolean{
			if (files.length == 0) return false;
			if (loadedFiles.length >= LOADED_FILES_ARRAY_MAX_LENGTH) return false;
			return true;
		}
		
		private function loadNewFile():void{
			if (!canWeLoadMoreFiles()) return;
			var file:FileReference = FileReference(files.getItemAt(0));
			files.removeItemAt(0);
			file.addEventListener(Event.COMPLETE, loadFileHandler);
			file.load();
		}
		private function loadFileHandler(event:Event):void{
			loadedFiles.push(event.target);
			event.target.removeEventListener(Event.COMPLETE, loadFileHandler);
			loadNewFile();
		}
		public function getFilesCount():int{
			return files.length;
		}
		public function finish():void{
			fileListst = new Array();
			files = new ArrayCollection();
			loadedFiles = new Array();		
		}
		public function removeFile(name:String):void{
			for(var i:int = 0; i < files.length; i++){
				if (FileReference(files.getItemAt(i)).name == name ){
					files.removeItemAt(i);
					return;
				} 
			}
		}		
	}
}